<template>
  <div class="hc-custom-report">
    <div :ref="reportId" :id="reportId" class="hc-custom-sheet"></div>
  </div>
</template>

<script>
import { mergeObjects, reOptions } from './components/config'
import { insertBarToolBeforeOrAfter } from './components/showinfobar'
import { clickEvent } from '../../event/eventClick'
import { EventBus } from '../HCEventBus/eventBus'
let exportExcelFunction;
async function loadExportExcel() {
  if (!exportExcelFunction) {
    // 动态导入 '../utils/export' 模块
    const module = await import('hc-core/utils/export');
    // 从模块中获取 exportExcel 函数
    exportExcelFunction = module.exportExcel;
  }
  return exportExcelFunction;
}
import LuckyExcel from 'luckyexcel'

export default {
  props: {
    // 报表ID标识
    reportId: {
      type: String,
      required: true
    },
    // 报表组件配置
    ctrlProps: {
      type: Object,
      required: false,
      default: {
        container: 'luckysheet',
        title: 'LuckySheet',
        data: [],
        lang: 'zh',
        showinfobar: false,
        showtoolbarConfig: [],
        customButtons: []
      }
    },
    // 双向绑定值
    value: {
      type: String,
      required: false
    },
    // 父级表单对象
    otherObj: {
      type: [Object, Function],
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      // Excel 配置参数
      excelConfig: {},
      // 鼠标悬停的单元格位置
      position: {},
      // 是否编辑
      isEdit: false
    }
  },
  watch: {
    // 监听鼠标悬停的单元格位置
    position: {
      handler: function(val) {
        // console.log(val,"====================")
      },
      deep: true
    },
    // 监听双向绑定值的变化
    value: {
      handler: function(newVal, oldVal) {
        if (newVal != oldVal && !this.isEdit) {
          // console.log('更新excel====================',this.excelConfig)
          this.$nextTick(_ => {
            // 初始化 LuckySheet 配置参数
            this.initLuckySheetConfig()
            // 初始化 LuckySheet
            this.initLuckySheet()
            // window.luckysheet.updataSheet(this.excelConfig);
          })
        } else {
          this.isEdit = false
        }
      },
      deep: true
    }
  },
  mounted() {
    // console.log('报表组件加载......')
    // 初始化 LuckySheet 配置参数
    this.initLuckySheetConfig()
    // 初始化 LuckySheet
    this.initLuckySheet()

    // 监听 EventBus，接收拖拽数据
    EventBus.$on('drag-data', this.insertDataToLuckySheet)

    // 添加 Ctrl + S 键盘事件监听
    window.addEventListener('keydown', this.handleKeydown)
  },
  beforeDestroy() {
    console.log('销毁 LuckySheet')
    // 销毁 LuckySheet
    window.luckysheet.destroy()

    // 组件销毁时注销监听器
    EventBus.$off('drag-data', this.insertDataToLuckySheet)

    // 移除 Ctrl + S 键盘事件监听
    window.removeEventListener('keydown', this.handleKeydown)
  },
  methods: {
    /**
     * 初始化 LuckySheet 配置参数
     */
    initLuckySheetConfig() {
      // 获取表单控件中的配置
      let ctrlProps = this.value ? JSON.parse(this.value) : JSON.parse(JSON.stringify(this.ctrlProps))
      // 获取默认配置
      let defaultOptions = JSON.parse(JSON.stringify(reOptions))
      // 合并配置
      let configOptions = mergeObjects(defaultOptions, ctrlProps, ['customButtons'])
      // 初始化配置
      this.excelConfig = {
        ...configOptions,
        container: this.reportId
      }
    },
    /**
     * 初始化 LuckySheet
     */
    initLuckySheet() {
      console.log('初始化 LuckySheet', this.excelConfig)
      this.$nextTick(_ => {
        // 移除之前的表格
        window.luckysheet.destroy()
        // 重新加载表格配置项
        window.luckysheet.create({
          ...this.excelConfig, // 使用初始化的配置
          hook: {
            // 设置单元格编辑后的回调
            cellUpdated: (r, c, value) => {
              // 单元格编辑后的回调
              // this.handleSheetChange(true)
            },
            /**
             * @description 所有单元格渲染之前执行的方法。在内部，这个方法加在了luckysheetDrawMain渲染表格之前
             * @param {Object} [data]: 当前工作表二维数组数据
             * @param {Object} [sheet]:当前sheet对象
             * @param {Object} [ctx]: 当前画布的context
             */
            cellAllRenderBefore: (data, sheet, ctx) => {
              this.handleSheetChange(true)
            },
            sheetCreateAfter: (sheet) => {
              this.handleSheetChange(true)
            },
            sheetCopyAfter: (sheet) => {
              this.handleSheetChange(true)
            },
            sheetHideAfter: (sheet) => {
              this.handleSheetChange(true)
            },
            sheetShowAfter: (sheet) => {
              this.handleSheetChange(true)
            },
            sheetMoveAfter: (sheet) => {
              this.handleSheetChange(true)
            },
            sheetDeleteAfter: (sheet) => {
              this.handleSheetChange(true)
            },
            sheetEditNameAfter: (sheet) => {
              this.handleSheetChange(true)
            },
            sheetEditColorAfter: (sheet) => {
              this.handleSheetChange(true)
            },
            sheetZoomAfter: (sheet) => {
              this.handleSheetChange(true)
            },
            // 设置表格中鼠标移动的回调
            sheetMousemove: (cell, position, sheet, moveState, ctx) => {
              // console.log(cell,position,"================cs")
              if (position) {
                this.position = position
              }
            },
            sheetMouseup: (cell, position, sheet, moveState, ctx) => {
              // console.log(cell,position,"================cs")
              if (position) {
                this.position = position
              }
            },
            cellDragStop: (cell, position, sheet, moveState, ctx) => {
              // console.log(cell,position,"================cs")
              if (position) {
                this.position = position
              }
            },
            /**
             * @param {Object | Array} [range]: 选区范围，可能为多个选区
             * @param {Object} [originData]: 要被粘贴的选区范围所对应的数据
             * @param {Object} [pasteData]: 要粘贴的数据
             */
            rangePasteAfter: (range, originData, pasteData) => {
              // this.handleSheetChange(true)
            }
          }
        })
        // 初始化自定义按钮
        if (this.ctrlProps && this.ctrlProps.customButtons) {
          let reportDom = this.$refs[this.reportId]
          for (let i = 0; i < this.ctrlProps.customButtons.length; i++) {
            let preBtn = this.ctrlProps.customButtons[i]
            let showPosition = preBtn.showPosition === 'action' || preBtn.showPosition === 'followButtonView' ||
            preBtn.showPosition === 'action|followButtonView' ? [] : showPosition ? preBtn.showPosition.split('|') : []
            insertBarToolBeforeOrAfter(reportDom, `#luckysheet-icon-${showPosition[0] || 'undo'}`, {
              id: preBtn.btnName,
              dataTips: preBtn.btnTitle,
              icon: preBtn.iconName,
              click: () => this.handleEvent(preBtn)
            }, showPosition[1] || 'before')
          }
        }
        console.log('当前初始化表格属性', window.luckysheet.toJson())
      })
    },
    /**
     * 处理表格内容修改
     */
    handleSheetChange(boolEdit) {
      this.isEdit = true
      // 获取当前的表格配置
      const newConfig = window.luckysheet.toJson()
      // console.log('表格已修改并更新到父组件', newConfig)
      // 将新配置传递给父组件
      this.$emit('input', JSON.stringify(newConfig))
      if (boolEdit) {
        this.$emit('editExcel', JSON.stringify(newConfig))
      }
      console.log('表格已修改并更新到父组件', newConfig)
    },
    /**
     * 事件处理函数
     */
    handleEvent(P_Btn) {
      // console.log(event, this.otherObj, '====================')
      // 先保存excel配置信息
      this.handleSave()
      if (P_Btn.btnEvent) {
        let otherObj = typeof this.otherObj == 'function' ? this.otherObj() : this.otherObj
        clickEvent({
          btnEvent: P_Btn.btnEvent,
          ...P_Btn.btnEvent
        }, otherObj.getFormParam(), otherObj)
      } else {
        let btnName = P_Btn.btnName
        switch (btnName) {
          case 'IMPORT':
            this.importExcelEvent()
            break
          case 'EXPORT':
            this.exportExcelEvent()
            break
          default:
            break
        }
      }
    },
    /**
     * 保存 Excel 文件配置
     */
    handleSave() {
      this.handleSheetChange()
    },
    /**
     * Ctrl + S 保存 Excel 文件
     * @param {KeyboardEvent} event
     */
    handleKeydown(event) {
      if (event.ctrlKey && event.key === 's') {
        // 阻止默认的保存行为
        event.preventDefault()

        // 触发自定义保存逻辑
        this.handleSave()
      }
    },
    /**
     * 将拖拽的数据插入到 Luckysheet 的单元格
     * @param {Object} draggedData 拖拽的数据
     */
    insertDataToLuckySheet(draggedData) {
      console.log('接收到拖拽数据', draggedData)
      let { value, label } = draggedData
      // 假设你希望将数据插入到第 0 行，第 0 列的单元格
      // 获取当前鼠标悬停的单元格
      const { row, col } = {
        row: this.position.r,
        col: this.position.c
      }
      console.log('当前鼠标悬停的单元格', row, col)
      // 将拖拽的数据插入到 Luckysheet 的单元格
      window.luckysheet.setCellValue(row, col, {
        v: value,
        m: label
      })
    },
    /**
     * 导入 Excel 文件
     */
    importExcelEvent() {
      let _this = this
      console.log('执行导入方法中...')
      let inputDom = document.createElement('input')
      inputDom.type = 'file'
      inputDom.click()
      inputDom.onchange = () => {
        let file = inputDom.files[0]
        let fileName = file.name
        let suffixArr = fileName.split('.'), suffix = suffixArr[suffixArr.length - 1]
        if (suffix !== 'xlsx') {
          alert('Currently only supports the import of xlsx files')
          return
        }
        // 导入 Excel 文件
        LuckyExcel.transformExcelToLucky(file, (exportJson, luckysheetfile) => {
          console.log(exportJson, 'exportJson')
          if (exportJson.sheets == null || exportJson.sheets.length === 0) {
            alert('Failed to read the content of the excel file, currently does not support xls files!')
            return
          }
          _this.sheets = exportJson.sheets
          window.luckysheet.destroy()
          // 重新初始化 LuckySheet
          _this.excelConfig = {
            ..._this.excelConfig,
            data: exportJson.sheets
          }
          _this.initLuckySheet()
        })
      }
    }
    ,
    /**
     * 导出 Excel 文件
     */
   async exportExcelEvent() {
      console.log('执行导出方法中...')
      const exportExcel = await loadExportExcel();
      exportExcel(window.luckysheet.getAllSheets(), this.excelConfig.title)
    }
  }
}
</script>

<style lang="scss" scoped>
.hc-custom-report {
  width: 100%;
  height: 100%;
  position: relative;

  .hc-custom-sheet {
    margin: 0;
    padding: 0;
    position: absolute;
    width: 100%;
    height: 100%;
  }
}
</style>
<style type="text/css">
.luckysheet .luckysheet_info_detail .luckysheet_info_detail_back,
.luckysheet .luckysheet_info_detail .luckysheet_info_detail_update,
.luckysheet .luckysheet_info_detail .luckysheet_info_detail_save {
    display: none;
}
</style>
